package com.xuexiang.xuidemo.page.base;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.utils.TextTool;

import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.slice.BaseAbilitySlice;

/**
 * BaseAbilitySlice, 初始化ActionBar
 * 子类的布局必须包含返回控件 id:iv_back, 标题Text id:tv_title, 可在xml中导入头部xml include include_layout_page_title
 * 子类必须设置注解@Page以表明当前页面标题
 *
 * @since 2021-03-23
 */
public abstract class BasePageAbilitySlice extends BaseAbilitySlice {
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(getLayoutId());
        initActionBar();
    }

    private void initActionBar() {
        findComponentById(ResourceTable.Id_iv_back).setClickedListener(component -> onBackPressed());
        Text title = findCastComponentById(ResourceTable.Id_tv_title);
        title.setTruncationMode(Text.TruncationMode.AUTO_SCROLLING);
        title.setAutoScrollingCount(Text.AUTO_SCROLLING_FOREVER);
        title.startAutoScrolling();
        Page page = PageUtils.getPage(getClass());
        title.setText(page.name());
        if (page.menuRes() != Page.NONE) {
            Image menuIv = findCastComponentById(ResourceTable.Id_iv_menu);
            menuIv.setPixelMap(page.menuRes());
            menuIv.setVisibility(Component.VISIBLE);
            menuIv.setClickedListener(this::onMenuClick);
        }
        if (!TextTool.isNullOrEmpty(page.subTitle())) {
            Text descTv = findCastComponentById(ResourceTable.Id_tv_desc);
            descTv.setVisibility(Component.VISIBLE);
            descTv.setText(page.subTitle());
        }
    }

    /**
     * 返回布局Id
     *
     * @return LayoutId
     */
    protected abstract int getLayoutId();

    /**
     * ActionBar右侧菜单点击事件回调,
     *
     * @param component 被点击的组件
     * @throws RuntimeException 子类如果设置了右侧菜单, 必须复写改方法, 否则将抛出该异常
     */
    protected void onMenuClick(Component component) {
        throw new RuntimeException("You should override this method, and don't call super.onMenuClick(Component)!");
    }

    /**
     * 在根布局节点以及子节点寻找符合id的组件
     *
     * @param resId 目标id
     * @param <T> 目标泛型
     * @return 目标
     */
    protected <T extends Component> T findCastComponentById(int resId) {
        // noinspection unchecked
        return (T) super.findComponentById(resId);
    }
}
